import Vue from 'vue'
import axios from 'axios'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

//// request拦截器
//service.interceptors.request.use(config => {
//config.headers['token'] = Vue.cookie.get('token')
//return config
//}, error => {
//return Promise.reject(error)
//})
//
// response拦截器
service.interceptors.response.use(response => {
if (response.data && response.data.code === 401) { // 401, token失效
    alert('请重新登录');
}
return response
}, error => {
return Promise.reject(error)
})

// http response 服务器响应拦截器，这里拦截401错误，并重新跳入登页重新获取token
service.interceptors.response.use(
    response => {
        return response;
    },
    error => {
    	if(error=="Error: Network Error"){
    		var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
				if(keys) {
					for(var i = keys.length; i--;)
						document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
				}
	    	router.replace({
	                        path: '/'
	                   })
	    	location.reload()
    	}
//  	
//      if (error.response) {
//          switch (error.response.status) {
//              case 500:
//                  // 这里写清除token的代码
////                  router.replace({
////                      path: 'login',
////                      query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
////                  })
//          }
//      }
//      return Promise.reject(error.response.data) 
    });


export default service
